// 自定义hooks---用在发布管理中
import { useEffect, useState } from "react";
import axios from "axios";
import { notification } from "antd";
export default function usePublish(type) {
  console.log(type);
  const [dataSource, setdataSource] = useState([]);
  const { username } = JSON.parse(localStorage.getItem("token"));
  useEffect(() => {
    axios(
      `/news?author=${username}&publishState=${type}&_expand=category`
    ).then((res) => {
      console.log(res.data);
      res.data.forEach((item) => {
        if (item.label) {
          item.title = item.label;
        }
      });
      console.log(res.data);
      setdataSource(res.data);
    });
  }, [username, type]);

  // 发布管理-->待发布--->发布事件
  const handlePublish = (id) => {
    // 移除当前页的哪一项
    setdataSource(dataSource.filter((item) => item.id !== id));
    axios
      .patch(`/news/${id}`, {
        publishState: 2,
        publishTime: Date.now(),
      })
      .then(() => {
        notification.info({
          message: "通知",
          description: "您可以到【发布管理/已发布】中查看您的新闻",
          placement: "bottomRight",
        });
      });
  };
  // 发布管理-->已发布--->下线事件
  const handleSunset = (id) => {
    setdataSource(dataSource.filter((item) => item.id !== id));
    axios
      .patch(`/news/${id}`, {
        publishState: 3,
      })
      .then(() => {
        notification.info({
          message: "通知",
          description: "您可以到【发布管理/已下线】中查看您的新闻",
          placement: "bottomRight",
        });
      });
  };
  // 发布管理-->已下线--->删除事件
  const handleDelete = (id) => {
    setdataSource(dataSource.filter((item) => item.id !== id));
    axios.delete(`/news/${id}`).then(() => {
      notification.info({
        message: "通知",
        description: '您已经删除"已下线"的新闻',
        placement: "bottomRight",
      });
    });
  };
  return {
    dataSource,
    // 导入三个方法
    handlePublish,
    handleSunset,
    handleDelete,
  };
}
